function trim(str) {
	/* Remove whitespaces */
	return str.replace(/^\s+|\s+$/g, '');
}

function leadZero(num) {
	/* Return number */
	if (num >= 10) return num;

	/* Return number with leading zero */
	return '0' + num;
}

function inArray(array, value) {
	/* Array loop */
	for (var i = 0; i < array.length; i++) {
		/* Compare values */
		if (array[i] == value)
			return true;
	}

	return false;
}

function checkClass(id, name) {
	var el = document.getElementById(id);

	/* Element not found */
	if (el == null)
		return null;

	var cname = el.className.split(' ');

	/* Check class names */
	for (var i = 0; i < cname.length; i++) {
		/* Class found */
		if (cname[i] == name)
			return true;
	}

	return false;
}

function getElementByClass(name, index) {
	if (index == undefined)
		index = 0;

	return document.getElementsByClassName(name)[index];
}

function removeElement(id) {
	var el = document.getElementById(id);

	/* Remove element */
	if (el && el.parentNode)
		el.parentNode.removeChild(el);
}

function getOption(key, variable) {
	chrome.extension.sendRequest({
		method: 'getLocalStorage',
		key: key
	}, function(response) {
		var value = response.data;

		/* Set default value */
		if (value == undefined)
			value = true;

		/* Set option */
		eval(variable + '=' + value);
	});
}

function createNotification(title, text) {
	chrome.extension.sendRequest({
		method: 'showNotification',
		title: title,
		text: text
	});
}

function imgRotate(degrees, canvas, img) {
	var cc = canvas.getContext('2d');
	var cw = img.width, ch = img.height;
	var cx = 0, cy = 0;

	/* Check degrees */
	switch (degrees) {
	case 90:
		cw = img.height;
		ch = img.width;
		cy = img.height * (-1);
		break;
	case 180:
		cx = img.width  * (-1);
		cy = img.height * (-1);
		break;
	case 270:
		cw = img.height;
		ch = img.width;
		cx = img.width * (-1);
		break;
	}

	/* Set dimensions */
	canvas.setAttribute('width',  cw);
	canvas.setAttribute('height', ch);

	/* Rotate and draw */
	cc.rotate(degrees * Math.PI / 180);
	cc.drawImage(img, cx, cy);

	/* Show canvas */
	img.style.display    = 'none';
	canvas.style.display = 'inline';
}

function tuentopTab() {
	var logout = document.getElementById('tab_logout');
	var tab    = document.getElementById('tab_tuentop');

	if (logout && !tab) {
		var li = document.createElement('li');
		var a  = document.createElement('a');

		/* Setup tab */
		li.setAttribute('id', 'tab_tuentop');

		a.setAttribute('href', 'http://ayudatbox.weebly.com/');
		a.setAttribute('target', '_blank');
		a.setAttribute('title', 'Ayuda TBox');
		a.innerHTML = 'Ayuda TBox';

		/* Append tab */
		li.appendChild(a);
		logout.parentNode.insertBefore(li, logout);
	}
}

function asyncLoading() {
	var load      = document.getElementById('load');
	var container = document.getElementById('container');

	/* Modify ad iframe */
	if (optAsyncTipbox) {
		var iframe = document.getElementById('ad_iframe');

		if (iframe) {
			var tip = getElementByClass('loadingTip');

			if (tip) tip.style.marginTop = 0;

			var x = (window.innerWidth  - iframe.offsetWidth)  / 2;
			var y = (window.innerHeight - iframe.offsetHeight) / 2;

			iframe.style.position   = 'absolute';
			iframe.style.left       = x + 'px';
			iframe.style.top        = y + 'px';
			iframe.style.padding    = '8px';
			iframe.style.background = '#ffffff';
			iframe.style.boxShadow  = '0 0 10px #424242';
			iframe.style.opacity    = '.95';
			iframe.style.zIndex     = 10000000;
		}
	}

	/* Modify loading layer */
	if (load) {
		load.style.position     = 'fixed';
		load.style.background   = '#ffffff';
		load.style.padding      = '8px';
		load.style.border       = '1px solid #000000';
		load.style.borderRadius = '4px';
		load.style.boxShadow    = '0 0 10px #424242';
	}

	/* Show container layer */
	if (container && container.style.visibility == 'hidden')
		container.style.visibility = 'visible';

	/* Set body overflow */
	document.body.style.overflowX = 'auto';
	document.body.style.overflowY = 'auto';
}

function fixedHeader() {
	var header  = document.getElementById('header');
	var content = getElementByClass('content');

	/* Modify header */
	if (header && content) {
		header.style.position  = 'fixed';
		header.style.width     = '100%';
		header.style.boxShadow = '0 0 8px #222222';
		header.style.zIndex    = 100000;

		content.style.paddingTop = '39px';
	}
}

function photoRotation() {
	var image  = document.getElementById('photo_image');
	var canvas = document.getElementById('icanvas');

	if (image && !canvas) {
		/* Create canvas */
		canvas = document.createElement('canvas');
		canvas.setAttribute('id', 'icanvas');
		canvas.style.display = 'none';

		image.parentNode.appendChild(canvas);

		var info = getElementByClass('infoContent');
		var line = document.createElement('p');
		var link;

		/* Create links */
		link = document.createElement('a');
		link.setAttribute('href', 'javascript:');
		link.innerHTML = 'Original';
		link.onclick = function() { imgRotate(0, canvas, image); }

		line.appendChild(link).appendChild(document.createElement('br'));

		link = document.createElement('a');
		link.setAttribute('href', 'javascript:');
		link.innerHTML = 'Girar 90';
		link.onclick = function() { imgRotate(90, canvas, image); }

		line.appendChild(link).appendChild(document.createElement('br'));

		link = document.createElement('a');
		link.setAttribute('href', 'javascript:');
		link.innerHTML = 'Girar 180';
		link.onclick = function() { imgRotate(180, canvas, image); }

		line.appendChild(link).appendChild(document.createElement('br'));

		link = document.createElement('a');
		link.setAttribute('href', 'javascript:');
		link.innerHTML = 'Girar 270';
		link.onclick = function() { imgRotate(270, canvas, image); }

		line.appendChild(link);

		line.style.marginTop = '8px';
		info.appendChild(line);

		/* Remove border */
		removeElement('photo_border');
	}
}

function radioTuner() {
	var places = document.getElementById('tab_places');
	var menu   = document.getElementById('radio_menu');
	var radios = document.getElementsByClassName('radio_opt');

	if (places && !menu) {
		/* Radio options */
		var json = {
			"overlay_config": {
				"id": "radio_header",
				"targetPoint": {
					"element": "radio_button_header",
					"position": "br",
					"offsetY": -6
				},
				"sourcePoint": { "position":"tr" },
				"hook": { "position":"tr" },
				"className": "overlayActions"
			},
			"items":
			[
				{
					"item_label": "<strong>Desactivar</strong>",
					"link_title": "none",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Cadena Cien",
					"link_title": "cadenacien",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Cadena Dial",
					"link_title": "cadenadial",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Cadena SER",
					"link_title": "cadenaser",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Cope",
					"link_title": "cope",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "EuropaFM",
					"link_title": "europafm",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "FlaixFM",
					"link_title": "flaixfm",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "KissFM",
					"link_title": "kissfm",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Los40",
					"link_title": "los40",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "MaximaFM",
					"link_title": "maximafm",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "M80 Radio",
					"link_title": "m80radio",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Radio Marca",
					"link_title": "radiomarca",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Radio Nacional",
					"link_title": "rne1",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Radio Clasica",
					"link_title": "rne2",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Radio 3",
					"link_title": "rne3",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				},
				{
					"item_label": "Rock and Gol",
					"link_title": "rockandgol",
					"link_href": "javascript:void();",
					"link_class": "radio_opt"
				}
			]
		};

		var li = document.createElement('li');
		var a  = document.createElement('a');

		/* Create menu entry */
		li.setAttribute('id', 'radio_menu');

		a.setAttribute('id', 'radio_button_header');
		a.setAttribute('href', 'javascript:void();');
		a.setAttribute('onclick', 'Web2MenuFactory.create(' + JSON.stringify(json) + '); return false;');
		a.className = 'more';
		a.innerHTML = '<span><span>Radio</span></span>';

		/* Append menu entry */
		li.appendChild(a);
		places.parentNode.insertBefore(li, places.nextSibling);
	}

	/* Register click event */
	for (var i = 0; i < radios.length; i++) {
		radios[i].onclick = function() {
			var div = document.getElementById('radio');
			var val = this.getAttribute('title');

			/* Create hidden radio */
			if (!div) {
				div = document.createElement('div');
				div.setAttribute('id', 'radio');
				div.style.visibility = 'hidden';

				document.body.appendChild(div);
			}

			/* Tune radio */
			switch (val) {
			case 'none':
				div.innerHTML = '';
				break;
			case 'cadenacien':
				div.innerHTML = '<iframe src="http://player.cadena100.es/"></iframe>';
				break;
			case 'cadenadial':
				div.innerHTML = '<iframe src="http://www.cadenadial.com/player/"></iframe>';
				break;
			case 'cadenaser':
				div.innerHTML = '<iframe src="http://www.cadenaser.com/player_radio.html"></iframe>';
				break;
			case 'cope':
				div.innerHTML = '<iframe src="http://www.cope.es/player.php5"></iframe>';
				break;
			case 'europafm':
				div.innerHTML = '<iframe src="http://www.europafm.com/directo/"></iframe>';
				break;
			case 'flaixfm':
				div.innerHTML = '<iframe src="http://www.flaixfm.cat/repro.php"></iframe>';
				break;  
			case 'kissfm':
				div.innerHTML = '<iframe src="http://www.kissfm.es/files/radio/radio.html"></iframe>';
				break;
			case 'los40':
				div.innerHTML = '<iframe src="http://www.los40.com/player/"></iframe>';
				break;
			case 'maximafm':
				div.innerHTML = '<iframe src="http://www.maxima.fm/multimedia/radios.html"></iframe>';
				break;
			case 'm80radio':
				div.innerHTML = '<iframe src="http://www.m80radio.com/multimedia/radios.html"></iframe>';
				break;  
			case 'radiomarca':
				div.innerHTML = '<iframe src="http://www.marca.com/deporte/popup/radiomarca/index.html"></iframe>';
				break;
			case 'rne1':
				div.innerHTML = '<iframe src="http://www.rtve.es/alacarta/live_radio_PopUp.shtml?id=3348&v=0.75&vp=&lang=es"></iframe>';
				break;
			case 'rne2':
				div.innerHTML = '<iframe src="http://www.rtve.es/alacarta/live_radio_PopUp.shtml?id=3343&v=0.75&vp=&lang=es"></iframe>';
				break;
			case 'rne3':
				div.innerHTML = '<iframe src="http://www.rtve.es/alacarta/live_radio_PopUp.shtml?id=3342&v=0.75&vp=&lang=es"></iframe>';
				break;
			case 'rockandgol':
				div.innerHTML = '<iframe src="http://www.rockandgol.net/player/"></iframe>';
				break;
			}
		};
	}
}

function widgetAS() {
	var appointments  = document.getElementById('appointments');
	var clasificacion = document.getElementById('clasificacion');

	if (appointments && !clasificacion) {
		var sidebar = appointments.parentNode;

		var block = document.createElement('div');
		var title = document.createElement('h2');
		var body  = document.createElement('div');

		/* Setup block */
		block.setAttribute('id', 'clasificacion');
		block.className = 'mod';
		title.innerHTML = 'Clasificaci&oacute;n de la Liga';
		body.innerHTML  = '<iframe src="' + chrome.extension.getURL('as.html') + '" width="200" height="550" frameborder="no" scrolling="no"></iframe>';

		/* Append block */
		block.appendChild(title);
		block.appendChild(body);
		sidebar.appendChild(block);
	}
}

function friendList() {
	var chat_home = document.getElementById('chat_home_module');
	var flist     = document.getElementById('home_friends_list');

	if (chat_home && !flist) {
		var h2  = document.createElement('h2');
		var div = document.createElement('div');
		var ul  = document.createElement('ul');

		/* Create list block */
		flist = document.createElement('div');
		flist.className = 'mod homeChat';
		flist.setAttribute('id', 'home_friends_list');

		/* Set block body */
		h2.innerHTML       = 'Amigos';
		div.className      = 'body';

		ul.style.clear     = 'both';
		ul.style.maxHeight = '250px';
		ul.style.overflow  = 'auto';

		/* Append elements */
		div.appendChild(ul);
		flist.appendChild(h2);
		flist.appendChild(div);

		chat_home.parentNode.insertBefore(flist, chat_home);

		/* Get friends list */
		getFriends(function(list) {
			var num = list.length - 1;

			for (var i = 0; i < num; i++) {
				var li = document.createElement('li');
				var a  = document.createElement('a');

				/* Set friend link */
				a.setAttribute('href', '#m=Profile&func=index&user_id=' + list[i].id);
				a.style.paddingLeft = '18px';
				a.style.color = '#515151';
				a.className   = 'new friends';
				a.innerHTML   = list[i].string;

				/* Set friend entry */
				li.style.padding = '3px';

				/* Append entry */
				li.appendChild(a);
				ul.appendChild(li);
			}

			h2.innerHTML += ' <span id="home_friends_counter" class="counter">(' + num + ')</span>';
		});
	}
}

function isLoading() {
	/* Check if page is loading */
	if (document.getElementById('load'))
		return true;

	return false;
}

function chatConnected() {
	/* Check header chat */
	var res = checkClass('chat_header_roster', 'hide') ;

	if (res) {
		/* Check home chat */
		res = checkClass('chat_home_roster', 'hide');
		if (res || res == null)
			return false;
	}

	return true;
}

function setCheckFlag() {
	/* Set flag */
	checkFlag = true;
}

function getFriends(callback) {
	var url = 'http://www3.tuenti.com/?m=Search&func=get_friends_for_data_source&ajax=1&store=0&ajax_target=canvas';

	/* GET request */
	XHR.get(url, function(data) {
		var div  = document.createElement('div');

		div.style.display = 'none';
		div.innerHTML = data;
		document.body.appendChild(div);

		/* Get friends array */
		var json = JSON.parse(document.getElementById('request_data').innerHTML);

		document.body.removeChild(div);

		/* Trigger callback */
		if (callback)
			callback(json['results']);
	});
}

function getFriendsChat(obj) {
	var arr = obj.getElementsByTagName('a');
	
	var cnt     = 0;
	var friends = [];

	/* Check if chat is connected */
	if (!chatConnected()) {
		/* Reset flags */
		checkFlag = timeoutFlag = false;
		return null;
	}

	/* Check flags */
	if (!checkFlag) {
		if (!timeoutFlag) {
			timeoutFlag = true;
			setTimeout('setCheckFlag()', 5000);
		}

		return null;
	}

	/* Retrieve friend entries */
	for (var i = 0; i < arr.length; i++) {
		/* Get friend name */
		if (arr[i].className == 'friend' &&
		    arr[i].parentNode.getAttribute('animating') == 'false') {
			var html  = arr[i].innerHTML;
			var match = html.match(/([^<]*)/);

			friends[cnt++] = trim(match[0]);
		}
	}

	return friends;
}

function checkFriendsChat() {
	/* Get friends list */
	var f = getFriendsChat(this);

	/* Chat not connected */
	if (f != null && friends != null) {
		/* Check for connections */
		for (var i = 0; i < f.length; i++) {
			if (!inArray(friends, f[i])) {
				createNotification(f[i], 'se ha conectado.');
				console.log('[Tuentop] Conectado: ' + f[i]);
			}
		}

		/* Check for disconnections */
		for (var i = 0; i < friends.length; i++) {
			if (!inArray(f, friends[i])) {
				createNotification(friends[i], 'se ha desconectado.');
				console.log('[Tuentop] Desconectado: ' + friends[i]);
			}
		}
	}

	/* Update friends list */
	friends = f;
}

function checkMessages() {
	var url = 'http://www3.tuenti.com/index.control.php';

	/* POST request */
	XHR.post(url, '', function(data) {
		var json = JSON.parse(data);
		var val  = undefined;

		/* Check updates */
		if (json['updates'])
			val = json['updates']['new_messages'];

		/* Check unread messages */
		if (val != undefined) {
			if (unreadMsg < val)
				createNotification('Nuevos Mensajes Privados', 'Tienes ' + val + ' mensajes sin leer.');

			unreadMsg = val;
		}
	});
}


/* Global friends list */
var friends = null;

/* Global flags */
var clockFlag   = false;
var checkFlag   = false;
var timeoutFlag = false;

/* Global variables */
var csfr       = undefined;
var unreadMsg  = 0;

/* Global options */
var optMonitorChat = undefined;
var optMonitorPriv = undefined;
var optTuentopTab  = undefined;
var optAsyncLoad   = undefined;
var optAsyncTipbox = undefined;
var optFriendList  = undefined;
var optFixedHeader = undefined;
var optPhotoDl     = undefined;
var optPhotoRotate = undefined;
var optFloatClock  = undefined;
var optRadioTuner  = undefined;
var optWidgetAS    = undefined;

/* Load options */
getOption('chat_monitor',  'optMonitorChat');
getOption('priv_monitor',  'optMonitorPriv');
getOption('tuentop_tab',   'optTuentopTab');
getOption('async_load',    'optAsyncLoad');
getOption('async_tipbox',  'optAsyncTipbox');
getOption('friend_list',   'optFriendList');
getOption('fixed_header',  'optFixedHeader');
getOption('photo_dl',      'optPhotoDl');
getOption('photo_rotate',  'optPhotoRotate');
getOption('float_clock',   'optFloatClock');
getOption('radio_tuner',   'optRadioTuner');
getOption('widget_as',     'optWidgetAS');


/* Page DOM changed */
document.addEventListener('DOMSubtreeModified', function(event) {
	/* Read CSFR value */
	if (!csfr) {
		var match = document.head.innerHTML.match(/CSFR: '([^']*)/);

		if (match && match[1])
			csfr = match[1];
	}

	/* Float clock */
	if (optFloatClock && !clockFlag) {
		setInterval('updateClock()', 1000);
		clockFlag = true;
	}

	/* Tuentop tab */
	tuentopTab();

	/* Quick friend list */
	if (optFriendList)
		friendList();

	/* Async loading */
	if (optAsyncLoad)
		asyncLoading();

	/* Fixed header */
	if (optFixedHeader)
		fixedHeader();

	/* Enable photo rotation */
	if (optPhotoRotate)
		photoRotation();

	/* Embedded radio tuner */
	if (optRadioTuner)
		radioTuner();

	/* AS widget */
	if (optWidgetAS)
		widgetAS();

	/* Enable photo saving */
	if (optPhotoDl) {
		var photo_action = document.getElementById('photo_action');

		if (photo_action) {
			/* Remove fake gif */
			removeElement('save_gif');

			/* Change style */
			photo_action.style.display = 'inline';
		}
	}

	/* Monitorize chat */
	if (optMonitorChat) {
		var roster_list = document.getElementById('chat_roster_list');

		if (roster_list)
			roster_list.addEventListener('DOMSubtreeModified', checkFriendsChat);
	}

	/* Monitorize messages */
	if (optMonitorPriv) {
		setInterval('checkMessages()', 5000);
		optMonitorPriv = false;
	}
});
